package edu.tsp.ga.selectors;

import edu.tsp.ga.Chromosome;
import edu.tsp.ga.FitnessFunction;
import edu.tsp.ga.Population;
import edu.tsp.ga.utils.RandomGenerator;

import java.util.ArrayList;
import java.util.List;

public class TournamentSelector implements Selector {

    private int num;
    private FitnessFunction fitnessFunction;

    public TournamentSelector(FitnessFunction fitnessFunction, int k) {
        this.num = k;
        this.fitnessFunction = fitnessFunction;
    }

    @Override
    public Chromosome select(Population population) {
        int size = population.getChromosomes().size();
        List<Chromosome> chromosomes = new ArrayList<>();
        for(int i = 0; i < num; i++) {
            chromosomes.add(population.getChromosomes().get(RandomGenerator.nextInt(size)));
        }
        double min = Double.MAX_VALUE;
        Chromosome winner = null;
        for(Chromosome chromosome : chromosomes) {
            double value = fitnessFunction.eval(chromosome);
            if(value < min) {
                min = value;
                winner = chromosome;
            }
        }
        return winner;
    }

}
